<style lang="less">
.search {
    .van-nav-bar__title {
        max-width: 100%;
        margin: auto;
        width: 300px;
    }
    .van-search {
        padding: 0;
    }
}
</style>
<template>
    <div class="home search">
        <header>
            <van-nav-bar left-arrow @click-left="$router.back()">
                <template #title>
                    <van-search
                        v-model="searchKey"
                        placeholder="请输入搜索关键词"
                        @search="onSearch"
                    />
                </template>
            </van-nav-bar>
        </header>
        <van-list @load="nextPage" :finished="finished">
            <div class="goods-list">
                <div class="col" v-for="g in goodsList" :key="g.id">
                    <router-link :to="'/detail?id=' + g.id">
                        <div class="goods-item">
                            <div class="goods-image">
                                <img :src="g.picture" alt="" />
                            </div>
                            <div class="goods-info">
                                <div class="goods-title">{{ g.id }} - {{ g.title }}</div>
                                <div class="clear-float">
                                    <div class="goods-price float-left">
                                        ￥ {{ g.price }}
                                    </div>
                                    <div class="goods-sell-count float-right">
                                        已售 {{ g.sell_count }} 件
                                    </div>
                                </div>
                            </div>
                        </div>
                    </router-link>
                </div>
            </div>
        </van-list>
    </div>
</template>
<script>
import api from '../components/api';
export default {
    data() {
        return {
            searchKey: "",
            finished:false,
            goodsList: [],
            currentPage:0,
        };
    },
    mounted(){
        this.searchKey = this.$route.query.key || ''
    },
    methods:{
        nextPage(){
            this.currentPage ++;
            if(this.currentPage > 2) {
                this.finished = true; // 已经加载完成
                return;
            }
            this.onSearch();
        },
        onSearch(){
            api.get("/goods/search?page=" + this.currentPage + "&key=" + this.searchKey).then(ret=>{
                if(ret.code == 0){
                        this.goodsList.push(...ret.data)
                }else{
                    alert(ret.message);
                }
            }).catch();
        }
    }
};
</script>
